package com.jhzn.geomap.controller;

import com.jhzn.geomap.model.Point;
import com.jhzn.geomap.service.PointService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/api/points")
@CrossOrigin // 处理跨域请求
public class PointController {
    private static final Logger logger = LoggerFactory.getLogger(PointController.class);
    private final PointService pointService;

    public PointController(PointService pointService) {
        this.pointService = pointService;
    }

    @PostMapping
    public Point createPoint(@RequestBody Map<String, Object> pointData) {
        logger.info("Creating point with data: {}", pointData);
        Point point = new Point();
        point.setName((String) pointData.get("name"));
        List<Double> coordinates = (List<Double>) pointData.get("coordinates");
        point.setLocation(String.format("POINT(%f %f)", coordinates.get(0), coordinates.get(1)));
        Point createdPoint = pointService.createPoint(point);
        logger.info("Point created with ID: {}", createdPoint.getId());
        return createdPoint;
    }

    @PutMapping("/{id}")
    public Point updatePoint(@PathVariable Long id, @RequestBody Map<String, Object> pointData) {
        logger.info("Updating point with ID: {} and data: {}", id, pointData);
        Point point = new Point();
        point.setId(id);
        point.setName((String) pointData.get("name"));
        List<Double> coordinates = (List<Double>) pointData.get("coordinates");
        point.setLocation(String.format("POINT(%f %f)", coordinates.get(0), coordinates.get(1)));
        Point updatedPoint = pointService.updatePoint(point);
        logger.info("Point updated with ID: {}", updatedPoint.getId());
        return updatedPoint;
    }

    @GetMapping
    public List<Point> getAllPoints() {
        List<Point> points = pointService.getAllPoints();
        logger.info("Fetched points: {}", points);
        return points;
    }

    @DeleteMapping("/{id}")
    public void deletePoint(@PathVariable Long id) {
        logger.info("Deleting point with ID: {}", id);
        pointService.deletePoint(id);
        logger.info("Point deleted with ID: {}", id);
    }
}